package primalgorithms.list;


public class _02RemoveNthFromEnd {
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        int len = getLen(head),index = len - n + 1;
        //倒数第n个结点，就是顺数第len-n+1个结点，下标是len-n
        if(index == 1){
            return head.next;
        }
        ListNode p = head;
        for (int i = 1;i < index - 1;i++){
            p = p.next;
        }
        p.next = p.next.next;
        return head;
    }

    private static int getLen(ListNode head) {
        int len = 0;
        ListNode p = head;
        while (p != null){
            len++;
            p = p.next;
        }
        return len;
    }
}
